<template>
	<view v-if="islogin == false">
		<view class="normal-login-container">
			<view class="login-form-content">
			  <view class="input-item flex align-center">
			    <view class="iconfont icon-user icon"></view>
			    <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
			  </view>
			  <view class="input-item flex align-center">
			    <view class="iconfont icon-password icon"></view>
			    <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="50" />
			  </view>
			  
			  <view class="action-btn">
				<button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round" >登录</button>
			  </view>
			</view>
		</view>
		
	</view>
	<view v-if="islogin == true">
		<view class="container">
			<view class="header" :style="'height:110rpx'">
				<view >
					在线用户：<span v-for="(item,ind) in onlineuser">{{ind == 0?'':'、'}}{{item}}</span>
				</view>
			</view>
			
			<view class="concent" style="height: 90%;padding-bottom:80rpx;margin-top: 10px;">
				<scroll-view :scroll-top="scrolltop" scroll-with-animation=true scroll-y class="content" style='height: 100%;padding-bottom:50px;'>
					<uni-card style="width:70%;" :style="'float:' + (item.fromuser == curruser?'right':'left')" v-for="(item,index) in msglist" :title="item.fromuser" :extra="item.sendtime">
						<text class="uni-body">{{item.msginfo}}</text>
						<template v-if="item.url != '' && item.url != undefined">
							<image :src="baseUrl+item.url"></image>
						</template>
					</uni-card>
				</scroll-view>
			</view>
			<view class="footer" style="color:#000;height:70px;display: flex;">
				<button type="warn" style="width:100px;vertical-align: middle;" @click="sendImg()">图片</button>
				<textarea style="text-align: left;padding:3px; color:#000;border:solid 1px #ccc;background-color:#fff;border-radius:7px;;height:50px;width:100%;" placeholder-style="" placeholder="" v-model="inputmsg"/>
				<button type="warn" style="width:100px;vertical-align: middle;" @click="sendMsg()">发送</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref,getCurrentInstance ,onMounted, onUpdated ,nextTick} from "vue";
	import { toast, showConfirm, tansParams } from '@/utils/common'
	import { doSendMsg,login} from '@/api/msgbox'
	import upload from '@/utils/upload'
	import {recursionCompressH5} from "@/utils/utils_img.js"
	
	import config from '@/config'
	let islogin = ref(false);
	let curruser = ref("");
	let inputmsg = ref("");//输入的信息
	let onlineuser = ref([]);
	let msglist = ref([])
	let scrolltop = ref(0);
	let baseUrl = ref(config.baseUrl);
	if (process.env.NODE_ENV === 'development') {
	  baseUrl.value = config.baseUrlKaifa
	} else {
	  baseUrl.value = config.baseUrl
	}
	
	let wsbaseUrl = ref(config.wsbaseUrl);
	if (process.env.NODE_ENV === 'development') {
	  wsbaseUrl.value = config.wsbaseUrlKaifa
	} else {
	  wsbaseUrl.value = config.wsbaseUrl
	}
	
	let loginForm = ref({});
	
	function handleLogin(){
		login(loginForm.value).then(res => {
			islogin.value = true;
			curruser.value = loginForm.value.username;
			chat()
		}).catch(() => {
		});
	}
	
	onUpdated(() => {
		nextTick(()=>{
			scrolltop.value = 1000;
		})
	})
	
	let ws;
	
	function chat(){
		ws = new WebSocket(wsbaseUrl.value + "/chat");
		ws.onopen = function(){
			console.log("===onopen===");
		}
		ws.onmessage = function(evt){
			console.log("===onmessage===");
			console.log("===evt===",evt.data);
			
			try{
				uni.vibrate({
					success: function () {
						console.log('success');
					}
				});
			}catch(e){
				console.log(e);
			}
			
			
			var obj = JSON.parse(evt.data);
			if(obj.msgtype == "system"){
				onlineuser.value = JSON.parse(obj.msginfo)
			}else if(obj.msgtype == "user"){
				let newarr = [];
				let arr = JSON.parse(obj.msginfo);
				for(let i = 0;i<arr.length;i++){
					let item = arr[i];
					newarr.push(item);
					
				}
				msglist.value = newarr;
				nextTick(()=>{
					scrolltop.value = scrolltop.value + 1000;
				})
				
			}
			console.log("===obj===",obj);
		}
		ws.onclose = function(){
			console.log("===onclose===");
		}
	}
	
	//发送消息
	function sendMsg(){
		let msg = {};
		msg.fromuser = curruser.value;
		msg.msginfo = inputmsg.value;
		msg.sendtime = getCurrentTime();
		inputmsg.value = "";//清空发送内容
		ws.send( JSON.stringify(msg));
		scrolltop.value = 100000
	}
	
	function getCurrentTime() {
	    var date = new Date();
	    var seperator2 = ":";
	    
	    var hours = date.getHours();
	    var minutes = date.getMinutes();
	    var seconds = date.getSeconds();
	    
	    if (hours >= 0 && hours <= 9) {
	    	hours = "0" + hours;
	    }
	    if (minutes >= 0 && minutes <= 9) {
	    	minutes = "0" + minutes;
	    }
	    if (seconds >= 0 && seconds <= 9) {
	    	seconds = "0" + seconds;
	    }
	    var currentdate = hours + seperator2 + minutes
	        + seperator2 +seconds;
	    return currentdate;
	}
	
	
	//发送图片
	function sendImg(){
		
		uni.chooseImage({
			count: 1, //默认9
			//sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sizeType: [ 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album','camera'], //从相册选择
			success: function (chooseImageRes) {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				
				recursionCompressH5(chooseImageRes.tempFilePaths[0],false,function(url){
					
					let data = {name: 'websocketimage', filePath: url}
					upload({
						url: '/websocket/sendimg',
						name: data.name,
						filePath: data.filePath,
						success: (uploadFileRes) => {
							
						}
					}).then(res => {
						console.log("res===",res);
						let msg = {};
						msg.fromuser = curruser.value;
						msg.msginfo = inputmsg.value;
						msg.url = res.imgUrl;
						msg.sendtime = getCurrentTime();
						inputmsg.value = "";//清空发送内容
						ws.send( JSON.stringify(msg));
						scrolltop.value = 100000
					})
				})
				
				
				
				
			}
		});
	}
	
</script>

<style lang="scss" scoped>
    .container {
        display: flex;
        flex-direction: column;
        height: 100vh;
    }

    .header {
        position: fixed;
		z-index: 1000;
        top: 0;
        left: 0;
        right: 0;
        background-color: rgb(91,137,254);
        color: #fff;
        height: auto;
        text-align: center;
    }
	.concent{
		position: fixed;
		top: 60;
		left: 0;
		right: 0;
	}
    .content {
        flex: 1;
        overflow: auto;
		border-radius: 7px;
    }
    .list-item {
        height: 80px;
        line-height: 80px;
        border: 1px solid red;
        text-align: center;
    }
    .footer {
        position: fixed;
		padding:10px;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
        background-color: rgb(91,137,254);
    }
	.css_btn{
		margin-top: 20px;
	}
	
	.normal-login-container {
	  width: 100%;
	
	  .logo-content {
	    width: 100%;
	    font-size: 21px;
	    text-align: center;
	    padding-top: 15%;
	
	    image {
	      border-radius: 4px;
	    }
	
	    .title {
	      margin-left: 10px;
	    }
	  }
		
	  .login-form-content {
	    text-align: center;
	    margin: 20px auto;
	    margin-top: 15%;
	    width: 80%;
	
	    .input-item {
	      margin: 20px auto;
	      background-color: #f5f6f7;
	      height: 45px;
	      border-radius: 20px;
	
	      .icon {
	        font-size: 38rpx;
	        margin-left: 10px;
	        color: #999;
	      }
	
	      .input {
	        width: 100%;
	        font-size: 14px;
	        line-height: 20px;
	        text-align: left;
	        padding-left: 15px;
	      }
	
	    }
	
	    .login-btn {
	      margin-top: 40px;
	      height: 45px;
	    }
	
	    .xieyi {
	      color: #333;
	      margin-top: 20px;
	    }
	    
	    .login-code {
	      height: 38px;
	      float: right;
	    
	      .login-code-img {
	        height: 38px;
	        position: absolute;
	        margin-left: 10px;
	        width: 200rpx;
	      }
	    }
	  }
	}
	
	.card-actions {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		padding-top:5px;
		border-top: 1px #eee solid;
	}
	
	.card-actions-item {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	
	.card-actions-item-text {
		font-size: 12px;
		color: #666;
		margin-left: 5px;
	}
	page {
	  background-color: #ffffff;
	}
	
	.normal-login-container {
	  width: 100%;
	
	  .logo-content {
	    width: 100%;
	    font-size: 21px;
	    text-align: center;
	    padding-top: 15%;
	
	    image {
	      border-radius: 4px;
	    }
	
	    .title {
	      margin-left: 10px;
	    }
	  }
	
	  .login-form-content {
	    text-align: center;
	    margin: 20px auto;
	    margin-top: 15%;
	    width: 80%;
	
	    .input-item {
	      margin: 20px auto;
	      background-color: #f5f6f7;
	      height: 45px;
	      border-radius: 20px;
	
	      .icon {
	        font-size: 38rpx;
	        margin-left: 10px;
	        color: #999;
	      }
	
	      .input {
	        width: 100%;
	        font-size: 14px;
	        line-height: 20px;
	        text-align: left;
	        padding-left: 15px;
	      }
	
	    }
	
	    .login-btn {
	      margin-top: 40px;
	      height: 45px;
	    }
	
	    .xieyi {
	      color: #333;
	      margin-top: 20px;
	    }
	    
	    .login-code {
	      height: 38px;
	      float: right;
	    
	      .login-code-img {
	        height: 38px;
	        position: absolute;
	        margin-left: 10px;
	        width: 200rpx;
	      }
	    }
	  }
	}
</style>
